package com.henz.web.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.ImplicitTransactionManagementPolicy;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import com.henz.web.domain.gcm.GCMMessage;
import com.henz.web.service.HenzReportService;
import com.henz.web.util.ConvertUtil;
import com.henz.web.util.gcm.GCMSender;
import com.henz.web.variable.HenzApp;
import com.henz.web.variable.HenzDB;


public class HenzReportServiceImpl implements HenzReportService {
	
	private Log logger = LogFactory.getLog(this.getClass());
	
	private static DatastoreServiceConfig config = 
			DatastoreServiceConfig.Builder.withImplicitTransactionManagementPolicy(ImplicitTransactionManagementPolicy.NONE);
	private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(config);
	

	@Override
	public List<Map<String, Object>> add(List<Map<String, Object>> reportList) throws Exception{
        
        Entity reportEntity = null;
        Key key = null;
        
        //http://maps.googleapis.com/maps/api/geocode/json?latlng=32.94583091642463,-96.71089571351617&sensor=true
		
        logger.info("saveReport=========");
        logger.info(reportList);
        /*
        String address = "";
        String url = "";
        String urlParameters = "";
        url = "http://maps.googleapis.com/maps/api/geocode/json";
        */
        
        
        if(reportList != null){
			datastore = DatastoreServiceFactory.getDatastoreService();
	        for(Map<String, Object> report:reportList){
	        	
	        	//urlParameters = "sensor=true&latlng=32.94583091642463,-96.71089571351617";
	        	/*
	        	urlParameters = ""
	        			+ "sensor=true"
	        			+ "&latlng=" + report.get("lat") + "," + report.get("long")
	        		;
	        	*/
	        	/*
	        	address = RequestUtil.sendPost(url, urlParameters);
	        	report.put("address", address);
	        	*/
	        	
	        	logger.info("saveReport user=========");
	            logger.info(report);
	            logger.info("saveReport user=========");
            	reportEntity = ConvertUtil.toEntity(HenzDB.HENZ_REPORT, "curTime", report);
            	
            	key = datastore.put(reportEntity);
            	
            	report.put("objKey", key.getId());
				
				//sendGCM(report);
				
			}
		}
        logger.info("saveReport=========");
		return reportList;
	}
	
	protected void sendGCM( Map<String, Object> report ) throws Exception{
        GCMMessage msg = new GCMMessage();
        
        msg.addRegId("APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93....");
        msg.createData("Test Title", "Test Message");
        
        logger.info("sendGCM=========");
        GCMSender.post(HenzApp.API_KEY, msg);
        logger.info("sendGCM=========");
	}

	@Override
	public void update(List<Map<String, Object>> userList) throws Exception{
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<Map<String, Object>> list() throws Exception{
		logger.info("findAllUsers=========");
		
		Query query = null;
		List<Entity> userResult = null;
		List<Map<String, Object>> userList = null;
		
		datastore = DatastoreServiceFactory.getDatastoreService();
		query = new Query(HenzDB.HENZ_REPORT)
			.addSort("date", Query.SortDirection.DESCENDING)
		;
		userResult = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));
	    
		userList = new ArrayList<Map<String, Object>>();
		logger.info("findAllUsers[" + userResult + "]");
		for( Entity userEntity : userResult ){
			userList.add(ConvertUtil.toMap(userEntity));
		}
		
		logger.info("findAllUsers=========");
		return userList;
	}

}
